# -*- coding: utf-8 -*-
"""
活动管理模块 - 数据模型
"""

from django.db import models
from django.core.validators import MinValueValidator
from django.utils import timezone
from django.conf import settings


class ActivityType(models.Model):
    """
    活动类型模型
    
    定义活动的分类，如运动健身、学习交流、亲子活动等
    """
    
    name = models.CharField(
        max_length=50,
        unique=True,
        verbose_name='类型名称',
        help_text='活动类型名称，如：运动健身、学习交流'
    )
    
    description = models.TextField(
        blank=True,
        verbose_name='类型描述',
        help_text='活动类型的详细描述'
    )
    
    # 是否为系统预设类型（系统类型不可删除）
    is_system = models.BooleanField(
        default=False,
        verbose_name='系统类型',
        help_text='是否为系统预设类型'
    )
    
    # 排序权重，数字越大越靠前
    sort_order = models.IntegerField(
        default=0,
        verbose_name='排序',
        help_text='排序权重，数字越大越靠前'
    )
    
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='创建时间'
    )
    
    class Meta:
        db_table = 'activity_types'
        verbose_name = '活动类型'
        verbose_name_plural = '活动类型'
        ordering = ['-sort_order', 'name']
    
    def __str__(self):
        return self.name


class Activity(models.Model):
    """
    活动模型 - 核心模型
    
    记录活动的所有信息，包括标题、描述、时间、地点、人数限制等
    """
    
    # 活动状态选择
    STATUS_CHOICES = [
        ('draft', '草稿'),
        ('published', '已发布'),
        ('ongoing', '进行中'),
        ('completed', '已完成'),
        ('cancelled', '已取消'),
    ]
    
    # 基本信息
    title = models.CharField(
        max_length=200,
        verbose_name='活动标题',
        help_text='活动的标题'
    )
    
    description = models.TextField(
        verbose_name='活动描述',
        help_text='活动的详细描述'
    )
    
    cover_image = models.ImageField(
        upload_to='activities/%Y/%m/',
        blank=True,
        null=True,
        verbose_name='封面图片',
        help_text='活动封面图片（自动存储到MinIO云存储）'
    )
    
    # 活动分类
    activity_type = models.ForeignKey(
        ActivityType,
        on_delete=models.SET_NULL,
        null=True,
        related_name='activities',
        verbose_name='活动类型'
    )
    
    # 活动创建者
    creator = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='created_activities',
        verbose_name='创建者',
        help_text='活动的创建者'
    )
    
    # 时间信息
    start_time = models.DateTimeField(
        verbose_name='开始时间',
        help_text='活动开始时间'
    )
    
    end_time = models.DateTimeField(
        verbose_name='结束时间',
        help_text='活动结束时间'
    )
    
    # 地点信息
    location_name = models.CharField(
        max_length=200,
        verbose_name='地点名称',
        help_text='活动地点名称，如：XX公园'
    )
    
    location_address = models.CharField(
        max_length=300,
        verbose_name='详细地址',
        help_text='活动地点详细地址'
    )
    
    # 地理坐标（用于地图显示和位置筛选）
    latitude = models.DecimalField(
        max_digits=10,
        decimal_places=7,
        verbose_name='纬度',
        help_text='活动地点纬度坐标'
    )
    
    longitude = models.DecimalField(
        max_digits=10,
        decimal_places=7,
        verbose_name='经度',
        help_text='活动地点经度坐标'
    )
    
    # 人数限制
    max_participants = models.IntegerField(
        validators=[MinValueValidator(1)],
        verbose_name='最大人数',
        help_text='活动最大参与人数'
    )
    
    current_participants = models.IntegerField(
        default=0,
        verbose_name='当前人数',
        help_text='当前已报名人数'
    )
    
    # 报名截止时间
    registration_deadline = models.DateTimeField(
        null=True,
        blank=True,
        verbose_name='报名截止时间',
        help_text='报名截止时间，不填则默认为活动开始前'
    )
    
    # 费用信息
    is_free = models.BooleanField(
        default=True,
        verbose_name='是否免费'
    )
    
    fee = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        default=0,
        verbose_name='活动费用',
        help_text='活动参与费用'
    )
    
    # 活动状态
    status = models.CharField(
        max_length=20,
        choices=STATUS_CHOICES,
        default='draft',
        verbose_name='活动状态'
    )
    
    # 统计信息
    view_count = models.IntegerField(
        default=0,
        verbose_name='浏览次数'
    )
    
    comment_count = models.IntegerField(
        default=0,
        verbose_name='评论数'
    )
    
    like_count = models.IntegerField(
        default=0,
        verbose_name='点赞数',
        help_text='活动获得的点赞总数'
    )
    
    rating_count = models.IntegerField(
        default=0,
        verbose_name='评分人数'
    )
    
    rating_average = models.DecimalField(
        max_digits=3,
        decimal_places=2,
        default=0,
        verbose_name='平均评分',
        help_text='活动平均评分（1-5星）'
    )
    
    # 是否支持团体报名
    allow_group_registration = models.BooleanField(
        default=False,
        verbose_name='允许团体报名'
    )
    
    # 团体报名优惠
    group_discount = models.DecimalField(
        max_digits=5,
        decimal_places=2,
        default=0,
        verbose_name='团体折扣',
        help_text='团体报名折扣，如0.9表示9折'
    )
    
    # 时间戳
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='创建时间'
    )
    
    updated_at = models.DateTimeField(
        auto_now=True,
        verbose_name='更新时间'
    )
    
    class Meta:
        db_table = 'activities'
        verbose_name = '活动'
        verbose_name_plural = '活动'
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['start_time']),
            models.Index(fields=['status']),
            models.Index(fields=['activity_type']),
            models.Index(fields=['latitude', 'longitude']),
        ]
    
    def __str__(self):
        return self.title
    
    def is_full(self):
        """判断活动是否已满"""
        return self.current_participants >= self.max_participants
    
    def can_register(self):
        """判断是否可以报名"""
        if self.is_full():
            return False
        if self.registration_deadline and timezone.now() > self.registration_deadline:
            return False
        if self.status not in ['published', 'ongoing']:
            return False
        return True


class ActivityRegistration(models.Model):
    """
    活动报名模型
    
    记录用户的活动报名信息
    """
    
    # 报名状态选择
    STATUS_CHOICES = [
        ('registered', '已报名'),
        ('cancelled', '已取消'),
        ('attended', '已参加'),
        ('absent', '缺席'),
    ]
    
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='registrations',
        verbose_name='用户'
    )
    
    activity = models.ForeignKey(
        Activity,
        on_delete=models.CASCADE,
        related_name='registrations',
        verbose_name='活动'
    )
    
    status = models.CharField(
        max_length=20,
        choices=STATUS_CHOICES,
        default='registered',
        verbose_name='报名状态'
    )
    
    # 报名备注
    note = models.TextField(
        blank=True,
        verbose_name='备注',
        help_text='用户报名时的备注信息'
    )
    
    # 是否已签到
    is_checked_in = models.BooleanField(
        default=False,
        verbose_name='是否签到'
    )
    
    # 签到时间
    check_in_time = models.DateTimeField(
        null=True,
        blank=True,
        verbose_name='签到时间'
    )
    
    # 团体报名相关
    group_registration = models.ForeignKey(
        'GroupRegistration',
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='members',
        verbose_name='所属团体'
    )
    
    # 时间戳
    registered_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='报名时间'
    )
    
    cancelled_at = models.DateTimeField(
        null=True,
        blank=True,
        verbose_name='取消时间'
    )
    
    updated_at = models.DateTimeField(
        auto_now=True,
        verbose_name='更新时间'
    )
    
    class Meta:
        db_table = 'activity_registrations'
        verbose_name = '活动报名'
        verbose_name_plural = '活动报名'
        unique_together = ('user', 'activity')
        ordering = ['-registered_at']
        indexes = [
            models.Index(fields=['activity', 'status']),
            models.Index(fields=['user', 'status']),
        ]
    
    def __str__(self):
        return f"{self.user.username} 报名 {self.activity.title}"


class GroupRegistration(models.Model):
    """
    团体报名模型
    
    允许多人一起报名同一活动
    """
    
    activity = models.ForeignKey(
        Activity,
        on_delete=models.CASCADE,
        related_name='group_registrations',
        verbose_name='活动'
    )
    
    leader = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='led_groups',
        verbose_name='团长',
        help_text='团体报名的负责人'
    )
    
    group_name = models.CharField(
        max_length=100,
        verbose_name='团体名称'
    )
    
    member_count = models.IntegerField(
        default=0,
        verbose_name='成员数量'
    )
    
    total_fee = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        default=0,
        verbose_name='总费用'
    )
    
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='创建时间'
    )
    
    class Meta:
        db_table = 'group_registrations'
        verbose_name = '团体报名'
        verbose_name_plural = '团体报名'
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.group_name} - {self.activity.title}"


class ActivityCheckIn(models.Model):
    """
    活动签到模型
    
    记录用户在活动现场的签到信息
    """
    
    registration = models.OneToOneField(
        ActivityRegistration,
        on_delete=models.CASCADE,
        related_name='checkin',
        verbose_name='报名记录'
    )
    
    # 签到地理位置（验证用户是否在活动现场）
    latitude = models.DecimalField(
        max_digits=10,
        decimal_places=7,
        verbose_name='签到纬度'
    )
    
    longitude = models.DecimalField(
        max_digits=10,
        decimal_places=7,
        verbose_name='签到经度'
    )
    
    # 签到设备信息
    device_info = models.CharField(
        max_length=200,
        blank=True,
        verbose_name='设备信息'
    )
    
    # 获得的积分奖励
    points_earned = models.IntegerField(
        default=0,
        verbose_name='获得积分'
    )
    
    checked_in_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='签到时间'
    )
    
    class Meta:
        db_table = 'activity_checkins'
        verbose_name = '活动签到'
        verbose_name_plural = '活动签到'
        ordering = ['-checked_in_at']
    
    def __str__(self):
        return f"{self.registration.user.username} 签到 {self.registration.activity.title}"


class ActivityLive(models.Model):
    """
    活动直播模型
    
    扩展功能 - 活动直播（可选实现）
    """
    
    # 直播状态
    STATUS_CHOICES = [
        ('scheduled', '待开始'),
        ('live', '直播中'),
        ('ended', '已结束'),
    ]
    
    activity = models.OneToOneField(
        Activity,
        on_delete=models.CASCADE,
        related_name='live',
        verbose_name='活动'
    )
    
    title = models.CharField(
        max_length=200,
        verbose_name='直播标题'
    )
    
    # 直播流地址
    stream_url = models.CharField(
        max_length=300,
        blank=True,
        verbose_name='直播流地址'
    )
    
    # 回放地址
    replay_url = models.CharField(
        max_length=300,
        blank=True,
        verbose_name='回放地址'
    )
    
    status = models.CharField(
        max_length=20,
        choices=STATUS_CHOICES,
        default='scheduled',
        verbose_name='直播状态'
    )
    
    # 统计信息
    viewer_count = models.IntegerField(
        default=0,
        verbose_name='观看人数'
    )
    
    peak_viewer_count = models.IntegerField(
        default=0,
        verbose_name='峰值人数'
    )
    
    start_time = models.DateTimeField(
        null=True,
        blank=True,
        verbose_name='开始时间'
    )
    
    end_time = models.DateTimeField(
        null=True,
        blank=True,
        verbose_name='结束时间'
    )
    
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='创建时间'
    )
    
    class Meta:
        db_table = 'activity_lives'
        verbose_name = '活动直播'
        verbose_name_plural = '活动直播'
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.activity.title} 直播"
